
let cfg = require('./utils/cfg');


// 管理所有的更新？
class Scheduler{
    constructor() {
        this._id = cfg.genId();

        this._tasks = {}; // taskId:Task
        this._targetTasks = {}; // targetId:[Task]
    }

    update(){
        let dt = cfg.gameApp.fps.dt;
        let tasks = this._tasks;
        let ids = Object.keys(tasks);
        ids.forEach(id=>{
            let task = tasks[id];
            if(task.valid && task.target.visible && task.target.enabled){
                task.update(dt);
            }
        });
    }

    addTask(task){
        if(!task.target){
            throw new Error(`task.target is null!`);
        }

        let arr = this._targetTasks[task.target.id];
        if(arr){
            // 检查一个相同的task是否存在
            for(let i = 0,len = arr.length; i < len; ++i){
                if(arr[i].equals(task)){
                    console.warn(`task:${task._func} already exist!`);
                    return;
                }
            }
        }else{
            arr = this._targetTasks[task.target.id] = [];
        }
        arr.push(task);
        this._tasks[task.id] = task;
    }

    removeTask(task){
        if(!task){
            throw new Error(`task is null!`);
        }
        if(!task.target){
            throw new Error(`task.target is null!`);
        }
        let arr = this._targetTasks[task.target.id];
        if(!arr){
            console.warn(`task.target 不存在 task!`);
        }
        for(let i = 0,len = arr.length; i < len; ++i){
            if(arr[i].equals(task) || arr[i].id === task){
                arr.splice(i,1);
                break;
            }
        }
        delete this._tasks[task.id];
    }

    removeAllTargetByNode(node){
        if(!node){
            throw new Error(`node is null!`);
        }
        let arr = this._targetTasks[node.id];
        if(!arr){
            return;
        }
        arr.forEach(task=>{
            delete this._tasks[task.id];
        });
        delete this._targetTasks[node.id];
    }

    getTask(node,func){
        if(!node || !func){
            throw new Error(`node or func is null!`);
        }
        let arr = this._targetTasks[node.id];
        if(!arr){
            return null;
        }
        for(let i = 0,len = arr.length; i < len; ++i){
            if(arr[i].target.id === node.id &&
               arr[i]._func === func){
                return arr[i];
            }
        }
        return  null;
    }
}

module.exports = Scheduler;
